# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: a1.py
"""
import requests
from lxml import etree
import ddddocr

class HuoSpider(object):
    def __init__(self):
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Origin': 'http://www.xxxx.com',
            'Pragma': 'no-cache',
            'Referer': 'http://www.xxxx.com/dgbak/auth/login',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        }
        self.auth_url = 'http://www.xxxx.com/dgbak/auth/login'
        self.session = requests.Session()
        self.ocr = ddddocr.DdddOcr()

    def get_captcha(self, captcha_url):
        response = self.request(captcha_url)
        text = self.ocr.classification(response)
        print(text)

        return text

    def request(self, url, data=None):
        if data:
            resp = self.session.post(url=url, headers=self.headers, data=data, verify=False)
        else:
            resp = self.session.get(url=url, headers=self.headers, verify=False)
        return resp.content

    def start_requests(self):
        response = self.request(self.auth_url)
        resp = etree.HTML(response)
        captcha_url = resp.xpath("//img[@class='captcha-img']/@src")
        _token = resp.xpath("//input[@name='_token']")
        token = _token.attrib.get("value")
        self.auth_requests(captcha_url, token)

    def auth_requests(self, captcha_url, token):
        data = {
            'username': '18611111111',
            'password': '12345612312312',
            'captcha': self.get_captcha(captcha_url),
            '_token': token,
        }
        response = self.request(self.auth_url, data=data)
        resp = etree.HTML(response)
        user_name = resp.xpath("//span[@class='hidden-xs']/text()")
        if user_name:
            print(f"登录后的用户名称: {user_name[0]}")


if __name__ == '__main__':
    hs = HuoSpider()
    hs.start_requests()